// $Id: XQueryOpenHandler.java 88 2012-03-01 15:33:37Z huijzer@gmail.com $
package lime.xquery.command;

import lime.common.LimeException;
import lime.xquery.editor.XQueryEditor;
import lime.xquery.view.XQueryParametersView;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.dialogs.ResourceListSelectionDialog;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.part.FileEditorInput;

public class XQueryOpenHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) {

		try {

			IWorkspace workspace = ResourcesPlugin.getWorkspace();
			IWorkspaceRoot workspaceRoot = workspace.getRoot();
			IProject project = workspaceRoot.getProject("lime");
			IFolder folder = project.getFolder("xquery");

			ResourceListSelectionDialog dialog = new ResourceListSelectionDialog(HandlerUtil.getActiveShell(event),
					folder, IResource.FILE);
			dialog.setTitle("Select XQuery");

			if (dialog.open() == Window.OK) {

				Object[] results = dialog.getResult();

				if (results.length > 0) {

					final IFile file = (IFile) results[0];
					final IEditorInput editorInput = new FileEditorInput(file);
					final IWorkbenchPage page = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
					final XQueryEditor editor = (XQueryEditor) page.openEditor(editorInput, "lime.xquery.editor");

					editor.getDocumentProvider().getDocument(editorInput).addDocumentListener(new IDocumentListener() {

						@Override
						public void documentChanged(DocumentEvent event) {
							XQueryParametersView view = (XQueryParametersView) page.findView(XQueryParametersView.ID);
							view.update(event.getDocument().get());
						}

						@Override
						public void documentAboutToBeChanged(DocumentEvent event) {
							// TODO Auto-generated method stub

						}
					});

				}

			}

		} catch (CoreException e) {
			throw new LimeException(e);
		}

		return null;

	}
}
